const tile = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8'
    })
})

var map = new ol.Map({
    target: 'map',
    layers: [tile],
    view: new ol.View({
        center: ol.proj.fromLonLat([107.11040599933166, 34.26271532332011]),
        zoom: 4,
        projection: 'EPSG:3857'
    })
});

const source = new ol.source.Vector({
    url: '/webgis-examples-code/book-examples/data/province.geojson',
    format: new ol.format.GeoJSON()
})
const vecLayer = new ol.layer.Vector({
    source: source,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: '#ff0000',
            width: 2
        }),
        fill: new ol.style.Fill({
            color: 'rgba(255,0,0,0.4)'
        })
    })
})
map.addLayer(vecLayer)

let canvas, ctx, resolutions = [];
// 切片原点
const origin = 20037508.342789244

class RasterTileRender {
    constructor() {
        canvas = document.createElement('canvas')
        canvas.classList.add('canvas-layer')
        const pNode = map.getViewport()
        pNode.appendChild(canvas)
        const {offsetWidth, offsetHeight} = pNode
        canvas.width = offsetWidth
        canvas.height = offsetHeight
        ctx = canvas.getContext('2d')
        // 设置全局透明度，为了方便与底图做对比
        ctx.globalAlpha = 0.8

        // 计算0-18的分辨率
        let resolution = 156543.03392804097
        for (let i = 0; i < 19; i++) {
            resolutions.push(resolution)
            resolution = resolution/ 2
        }

        // 注册map事件
        map.on('movestart', () => {
            ctx.clearRect(0,0, canvas.width, canvas.height)
        })
        map.on('moveend', () => {
            this.renderTiles()
        })
    }

    renderTiles() {
        // 获取地图级别及当前级别分辨率
        const z = Math.ceil(map.getView().getZoom())
        const res = resolutions[z]
        const val = res * 256

        // 获取地图范围
        const [xmin, ymin, xmax, ymax] = map.getView().calculateExtent()
        const xOrigin = -origin

        // 计算切片x和y方向的范围
        const _xmin = Math.floor((xmin - xOrigin) / val)
        const _xmax = Math.ceil((xmax - xOrigin) / val)
        const _ymin = Math.floor((origin - ymax) / val)
        const _ymax = Math.ceil((origin - ymin) / val)

        let getExtentFromXy = function (x, y) {
            return [
                xOrigin + x * val,
                origin - (y + 1) * val,
                xOrigin + (x + 1) * val,
                origin - y * val
            ]
        }

        for (let x = _xmin; x <= _xmax; x++) {
            for (let y = _ymin; y <= _ymax; y++) {
                const coords = getExtentFromXy(x, y)
                setTimeout(() => {
                    this.renderTile(x, y, z, coords)
                })
            }
        }
    }

    renderTile(x, y, z, coords) {
        const img = new Image()
        img.src = `https://webst01.is.autonavi.com/appmaptile?style=6&x=${x}&y=${y}&z=${z}`
        const [xmin, ymin, xmax, ymax] = coords
        const [_xmin, _ymin] = map.getPixelFromCoordinate([xmin, ymax])
        const [_xmax, _ymax] = map.getPixelFromCoordinate([xmax, ymin])
        const sw = _xmax - _xmin
        const sh = _ymax - _ymin
        img.onload = () => {
            ctx.drawImage(img, _xmin, _ymin, sw, sh)
        }
    }
}

const rasterTileRender = new RasterTileRender(map)

